<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TrainingScenario extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'description', 'objective', 'success_criteria',
        'scenario_prompt', 'tags', 'difficulty_level', 'is_active'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_active' => 'boolean',
        'created_at' => 'datetime',
    ];

    /**
     * 训练会话关系
     */
    public function trainingSessions()
    {
        return $this->hasMany(TrainingSession::class, 'scenario_id');
    }

    /**
     * JSON字段的访问器和修改器
     */
    public function getSuccessCriteriaAttribute($value)
    {
        return $value ? json_decode($value, true) : null;
    }

    public function setSuccessCriteriaAttribute($value)
    {
        $this->attributes['success_criteria'] = $value ? json_encode($value) : null;
    }

    /**
     * 获取标签数组
     */
    public function getTagsArrayAttribute()
    {
        return $this->tags ? explode(',', $this->tags) : [];
    }

    /**
     * 设置标签数组
     */
    public function setTagsArrayAttribute($value)
    {
        $this->attributes['tags'] = is_array($value) ? implode(',', $value) : $value;
    }

    /**
     * 获取难度等级文本
     */
    public function getDifficultyTextAttribute()
    {
        $levels = [
            1 => '新手',
            2 => '初级',
            3 => '中级',
            4 => '高级',
            5 => '专家'
        ];

        return $levels[$this->difficulty_level] ?? '未知';
    }

    /**
     * 作用域：活跃的场景
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 作用域：按难度筛选
     */
    public function scopeByDifficulty($query, $difficulty)
    {
        return $query->where('difficulty_level', $difficulty);
    }
}